package com.woniuxy.woniuticket.moviemodule.controller;

import com.woniuxy.woniuticket.moviemodule.constant.SystemConstant;
import com.woniuxy.woniuticket.moviemodule.service.AdminService;
import com.woniuxy.woniuticket.pojo.CinemaLogin;
import com.woniuxy.woniuticket.resultcommon.JsonResult;
import com.woniuxy.woniuticket.utils.ImageUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 赵晓东 on 2019/6/18/018.
 */
@Controller
@RequestMapping("/cinemaAdmin")
public class AdminController {
    @Autowired
    private AdminService adminService;

    //登陆
    @RequestMapping("/adminLogin")
    @ResponseBody
    public JsonResult login(CinemaLogin user, HttpSession httpSession, String ckeckcode) {
        if (((String) httpSession.getAttribute("validateCode")).equalsIgnoreCase(ckeckcode)) {
            //创建用户门面
            Subject subject = SecurityUtils.getSubject();
            //载入用户名和密码
            UsernamePasswordToken token = new UsernamePasswordToken(user.getAccount(), user.getPassword());
            try {
                subject.login(token);
                //登陆成功后，查询用户信息，并存入session
                CinemaLogin dbUser = adminService.login(user.getAccount());
                Session session = subject.getSession();
                session.setAttribute(SystemConstant.CURRENT_USER, dbUser);
                httpSession.setAttribute("currentUser", dbUser);
            } catch (UnknownAccountException e) {
                return JsonResult.error("账号错误！");
            } catch (IncorrectCredentialsException e) {
                return JsonResult.error("密码错误！");
            } catch (LockedAccountException e) {
                return JsonResult.error("账号被锁定！");
            } catch (AuthenticationException e) {
                return JsonResult.error("认证时出现异常，具体原因未知！");
            }
            return JsonResult.ok("登录成功");
        }
        return JsonResult.error("请输入正确的验证码！");
    }


    //查询个人信息
    @RequestMapping("/findUser")
    @ResponseBody
    public Map findUser(){

        Map<String,Object> map = new HashMap<>();
        //创建用户门面
        Subject subject = SecurityUtils.getSubject();
        CinemaLogin user = (CinemaLogin) subject.getSession().getAttribute(SystemConstant.CURRENT_USER);
        if(user!=null){
            map.put("code",200);
            map.put("token","taVJM3Ba3lBTr/LSsoiAsv+Qd2Qt8j4d");
            map.put("msg","查询成功");
            ArrayList<CinemaLogin> list = new ArrayList<>();
            list.add(user);
            map.put("data",list);
            return map;
        }else{
            map.put("code",500);
            map.put("msg","查询失败");
            return map;
        }
    }


    //修改或者删除
    @RequestMapping("/update")
    @ResponseBody
    public JsonResult update(CinemaLogin user,String usedPwd,HttpSession session){
        if(user.getAccount()!="" || user.getPassword()!="" || usedPwd!=""){
            //获取当前用户
            CinemaLogin currentUser = (CinemaLogin) session.getAttribute("currentUser");
            //验证用户身份
            if(currentUser.getPassword().equals(new Md5Hash(usedPwd, user.getAccount(), 2).toString())){
               CinemaLogin cin = new CinemaLogin();
                //密码加密
                cin.setPassword(new Md5Hash(user.getPassword(), user.getAccount(), 2).toString());
                cin.setId(currentUser.getId());
                int row = adminService.update(cin);
                if(row > 0){
                    return JsonResult.ok();
                }else{
                    return JsonResult.error("修改失败！");
                }

            }
            return JsonResult.error("请输入正确的旧密码！");
        }
        return JsonResult.error("密码或用户名不能为空！");
    }

    //密码校验
    @RequestMapping("/checkPwd")
    @ResponseBody
    public JsonResult checkPwd(CinemaLogin user){
        //创建用户门面
        Subject subject = SecurityUtils.getSubject();
        CinemaLogin currentUser = (CinemaLogin)subject.getSession().getAttribute(SystemConstant.CURRENT_USER);
        if(currentUser.getPassword().equals(new Md5Hash(user.getPassword(), user.getAccount(), 2).toString())){
            return JsonResult.ok();
        }
        return JsonResult.error();

    }

    // 生成验证码图片
    @ResponseBody
    @RequestMapping(value = "/checkCode", method = RequestMethod.GET)
    public void validateCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 第一个参数是生成的验证码，第二个参数是生成的图片
        Object[] objs = new ImageUtil().createImage();
        // 将验证码存入Session
        request.getSession(true).setAttribute("validateCode", objs[0]);
        // 将图片输出给浏览器
        BufferedImage image = (BufferedImage) objs[1];
        // 禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        OutputStream os = response.getOutputStream();
        ImageIO.write(image, "jpeg", os);
        os.flush();
    }
}
